<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="采购单号" prop="purchaseOrderNo">
        <el-input
          v-model="queryParams.purchaseOrderNo"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="药品名称" prop="drugName">
          <el-input
            v-model="queryParams.drugName"
            placeholder="请输入药品名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      <el-form-item label="验收状态" prop="acceptanceStatus">
        <el-select v-model="queryParams.acceptanceStatus" placeholder="请选择验收状态" clearable>
          <el-option label="待验收" value="待验收" />
          <el-option label="通过" value="通过" />
          <el-option label="失败" value="失败" />
        </el-select>
      </el-form-item>
      <el-form-item label="采购日期" prop="purchaseDate">
        <el-date-picker
          v-model="queryParams.purchaseDate"
          type="date"
          placeholder="选择采购日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['veterinary:purchase:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['veterinary:purchase:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['veterinary:purchase:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['veterinary:purchase:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handlePending"
        >待验收</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
      <template slot="empty">
        <div class="empty-data">
          <i class="el-icon-box"></i>
          <p>暂无数据</p>
        </div>
      </template>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购单号" align="center" prop="purchaseOrderNo" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" :show-overflow-tooltip="true" />
      <el-table-column label="药品名称" align="center" prop="drugName" :show-overflow-tooltip="true" />
      <el-table-column label="规格" align="center" prop="drugSpecification" />
      <el-table-column label="厂家" align="center" prop="manufacturerName" :show-overflow-tooltip="true" />
      <el-table-column label="兽药批号" align="center" prop="batchNumber" />
      <el-table-column label="进价" align="center" prop="purchasePrice">
        <template slot-scope="scope">
          <span>¥{{ parseFloat(scope.row.purchasePrice).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="总金额" align="center" prop="totalAmount">
        <template slot-scope="scope">
          <span>¥{{ parseFloat(scope.row.totalAmount).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购日期" align="center" prop="purchaseDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="验收状态" align="center" prop="acceptanceStatus">
        <template slot-scope="scope">
          <el-tag 
            :type="getAcceptanceStatusType(scope.row.acceptanceStatus)"
          >
            {{ scope.row.acceptanceStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="验收人" align="center" prop="acceptor" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['veterinary:purchase:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.acceptanceStatus === '待验收'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAcceptance(scope.row)"
            v-hasPermi="['veterinary:purchase:edit']"
          >验收</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['veterinary:purchase:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改进货管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购单号" prop="purchaseOrderNo">
              <el-input v-model="form.purchaseOrderNo" placeholder="系统自动生成" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable>
                <el-option
                  v-for="supplier in supplierList"
                  :key="supplier.supplierId"
                  :label="supplier.supplierName"
                  :value="supplier.supplierId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="药品名称" prop="drugName">
          <el-row :gutter="10">
            <el-col :span="18">
              <el-input v-model="form.drugName" placeholder="请输入药品名称" />
            </el-col>
            <el-col :span="6">
              <el-button type="primary" icon="el-icon-search" @click="openInventorySelector">选择库存</el-button>
            </el-col>
          </el-row>
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="drugSpecification">
              <el-input v-model="form.drugSpecification" placeholder="如：10%/100g/袋" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="药品厂家" prop="manufacturerId">
              <el-select v-model="form.manufacturerId" placeholder="请选择药品厂家" filterable>
                <el-option
                  v-for="manufacturer in manufacturerList"
                  :key="manufacturer.manufacturerId"
                  :label="manufacturer.manufacturerName"
                  :value="manufacturer.manufacturerId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="兽药批号" prop="batchNumber">
              <el-input v-model="form.batchNumber" placeholder="请输入兽药批号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="进价" prop="purchasePrice">
              <el-input-number v-model="form.purchasePrice" :precision="2" :step="0.1" :min="0" placeholder="请输入进价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="form.quantity" :min="1" placeholder="请输入数量" @change="calculateTotal" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总金额" prop="totalAmount">
              <el-input v-model="form.totalAmount" placeholder="自动计算" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                placeholder="选择采购日期"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票号" prop="invoiceNumber">
              <el-input v-model="form.invoiceNumber" placeholder="请输入发票号" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 验收对话框 -->
    <el-dialog title="药品验收" :visible.sync="acceptanceOpen" width="600px" append-to-body>
      <el-form ref="acceptanceForm" :model="acceptanceForm" :rules="acceptanceRules" label-width="100px">
        <el-form-item label="采购单号">
          <el-input v-model="acceptanceForm.purchaseOrderNo" readonly />
        </el-form-item>
        <el-form-item label="药品名称">
          <el-input v-model="acceptanceForm.drugName" readonly />
        </el-form-item>
        <el-form-item label="验收状态" prop="acceptanceStatus">
          <el-radio-group v-model="acceptanceForm.acceptanceStatus">
            <el-radio label="通过">通过</el-radio>
            <el-radio label="失败">失败</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="验收人" prop="acceptor">
          <el-input v-model="acceptanceForm.acceptor" placeholder="请输入验收人" />
        </el-form-item>
        <el-form-item label="验收结果" prop="acceptanceResult">
          <el-input v-model="acceptanceForm.acceptanceResult" type="textarea" placeholder="请输入验收结果（外观/批号/有效期验收结果）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAcceptance">确 定</el-button>
        <el-button @click="cancelAcceptance">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 待验收列表对话框 -->
    <el-dialog title="待验收采购单" :visible.sync="pendingOpen" width="1200px" append-to-body>
      <el-table :data="pendingList" style="width: 100%">
        <el-table-column label="采购单号" prop="purchaseOrderNo" />
        <el-table-column label="供应商" prop="supplierName" />
        <el-table-column label="药品名称" prop="drugName" />
        <el-table-column label="规格" prop="drugSpecification" />
        <el-table-column label="数量" prop="quantity" />
        <el-table-column label="采购日期" prop="purchaseDate">
          <template slot-scope="scope">
            {{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleAcceptance(scope.row)"
            >验收</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 库存商品选择对话框 -->
    <el-dialog title="选择库存商品" :visible.sync="inventorySelectorOpen" width="1000px" append-to-body>
      <el-form :model="inventoryQuery" ref="inventoryQueryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="药品名称" prop="drugName">
          <el-input
            v-model="inventoryQuery.drugName"
            placeholder="请输入药品名称"
            clearable
            @keyup.enter.native="getInventoryList"
          />
        </el-form-item>
        <el-form-item label="批号" prop="batchNumber">
          <el-input
            v-model="inventoryQuery.batchNumber"
            placeholder="请输入批号"
            clearable
            @keyup.enter.native="getInventoryList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getInventoryList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetInventoryQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table 
        :data="inventoryList" 
        style="width: 100%" 
        @row-click="selectInventoryItem"
        highlight-current-row
      >
        <el-table-column label="药品名称" prop="drugName" />
        <el-table-column label="规格" prop="drugSpecification" />
        <el-table-column label="批号" prop="batchNumber" />
        <el-table-column label="库存数量" prop="quantity" />
        <el-table-column label="进价" prop="purchasePrice">
          <template slot-scope="scope">
            <span>¥{{ parseFloat(scope.row.purchasePrice || 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="适用动物" prop="applicableAnimals" />
        <el-table-column label="疾病类型" prop="diseaseType" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="selectInventoryItem(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="inventoryTotal>0"
        :total="inventoryTotal"
        :page.sync="inventoryQuery.pageNum"
        :limit.sync="inventoryQuery.pageSize"
        @pagination="getInventoryList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase, generateOrderNo, getPendingList, processAcceptance } from "@/api/veterinary/purchase";
import { listInventory } from "@/api/veterinary/inventory";

export default {
  name: "Purchase",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 进货管理表格数据
      purchaseList: [],
      // 待验收列表
      pendingList: [],
      // 供应商列表
      supplierList: [],
      // 药品厂家列表
      manufacturerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示验收对话框
      acceptanceOpen: false,
      // 是否显示待验收对话框
      pendingOpen: false,
      // 是否显示库存选择对话框
      inventorySelectorOpen: false,
      // 库存列表
      inventoryList: [],
      // 库存总条数
      inventoryTotal: 0,
      // 库存查询参数
      inventoryQuery: {
        pageNum: 1,
        pageSize: 10,
        drugName: null,
        batchNumber: null
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaseOrderNo: null,
        supplierId: null,
        drugName: null,
        drugSpecification: null,
        manufacturerId: null,
        batchNumber: null,
        acceptanceStatus: null,
        purchaseDate: null,
      },
      // 表单参数
      form: {
        purchaseId: null,
        purchaseOrderNo: null,
        supplierId: null,
        drugName: null,
        drugSpecification: null,
        manufacturerId: null,
        batchNumber: null,
        purchasePrice: null,
        quantity: null,
        purchaseDate: null,
        acceptanceStatus: "待验收",
        acceptanceResult: null,
        acceptor: null,
        acceptanceDate: null,
        invoiceNumber: null,
        invoiceImage: null,
        totalAmount: null
      },
      // 验收表单参数
      acceptanceForm: {},
      // 表单校验
      rules: {
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
        drugName: [
          { required: true, message: "药品名称不能为空", trigger: "blur" }
        ],
        drugSpecification: [
          { required: true, message: "规格不能为空", trigger: "blur" }
        ],
        manufacturerId: [
          { required: true, message: "药品厂家不能为空", trigger: "change" }
        ],
        batchNumber: [
          { required: true, message: "兽药批号不能为空", trigger: "blur" }
        ],
        purchasePrice: [
          { required: true, message: "进价不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        purchaseDate: [
          { required: true, message: "采购日期不能为空", trigger: "change" }
        ]
      },
      // 验收表单校验
      acceptanceRules: {
        acceptanceStatus: [
          { required: true, message: "验收状态不能为空", trigger: "change" }
        ],
        acceptor: [
          { required: true, message: "验收人不能为空", trigger: "blur" }
        ],
        acceptanceResult: [
          { required: true, message: "验收结果不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getSupplierList();
    this.getManufacturerList();
  },
  methods: {
    /** 查询进货管理列表 */
    getList() {
      this.loading = true;
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取供应商列表 */
    getSupplierList() {
      import("@/api/veterinary/supplier").then(supplierApi => {
        supplierApi.listSupplier({}).then(response => {
          this.supplierList = response.rows || [];
        }).catch(() => {
          // 如果API调用失败，使用模拟数据
          this.supplierList = [
            { supplierId: 1, supplierName: "北京兽药批发有限公司" },
            { supplierId: 2, supplierName: "上海动物保健品经营部" },
            { supplierId: 3, supplierName: "南方兽药批发中心" }
          ];
        });
      }).catch(() => {
        // 如果模块加载失败，使用模拟数据
        this.supplierList = [
          { supplierId: 1, supplierName: "北京兽药批发有限公司" },
          { supplierId: 2, supplierName: "上海动物保健品经营部" },
          { supplierId: 3, supplierName: "南方兽药批发中心" }
        ];
      });
    },
    /** 获取厂家列表 */
    getManufacturerList() {
      import("@/api/veterinary/manufacturer").then(manufacturerApi => {
        manufacturerApi.listManufacturer({}).then(response => {
          this.manufacturerList = response.rows || [];
        }).catch(() => {
          // 如果API调用失败，使用模拟数据
          this.manufacturerList = [
            { manufacturerId: 1, manufacturerName: "华畜兽药有限公司" },
            { manufacturerId: 2, manufacturerName: "康达生物制药" },
            { manufacturerId: 3, manufacturerName: "绿康动保科技" }
          ];
        });
      }).catch(() => {
        // 如果模块加载失败，使用模拟数据
        this.manufacturerList = [
          { manufacturerId: 1, manufacturerName: "华畜兽药有限公司" },
          { manufacturerId: 2, manufacturerName: "康达生物制药" },
          { manufacturerId: 3, manufacturerName: "绿康动保科技" }
        ];
      });
    },
    /** 获取验收状态标签类型 */
    getAcceptanceStatusType(status) {
      const statusMap = {
        '待验收': 'warning',
        '通过': 'success',
        '失败': 'danger'
      };
      return statusMap[status] || 'info';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 验收取消按钮
    cancelAcceptance() {
      this.acceptanceOpen = false;
      this.resetAcceptance();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseId: null,
        purchaseOrderNo: null,
        supplierId: null,
        drugName: null,
        drugSpecification: null,
        manufacturerId: null,
        batchNumber: null,
        purchasePrice: null,
        quantity: null,
        purchaseDate: null,
        acceptanceStatus: "待验收",
        acceptanceResult: null,
        acceptor: null,
        acceptanceDate: null,
        invoiceNumber: null,
        invoiceImage: null,
        totalAmount: null
      };
      this.resetForm("form");
    },
    // 验收表单重置
    resetAcceptance() {
      this.acceptanceForm = {
        purchaseId: null,
        purchaseOrderNo: null,
        drugName: null,
        acceptanceStatus: null,
        acceptor: null,
        acceptanceResult: null
      };
      this.resetForm("acceptanceForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 生成采购单号
      generateOrderNo().then(response => {
        this.form.purchaseOrderNo = response.data;
        this.open = true;
        this.title = "添加采购信息";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const purchaseId = row.purchaseId || this.ids
      getPurchase(purchaseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购信息";
      });
    },
    /** 验收按钮操作 */
    handleAcceptance(row) {
      this.resetAcceptance();
      this.acceptanceForm.purchaseId = row.purchaseId;
      this.acceptanceForm.purchaseOrderNo = row.purchaseOrderNo;
      this.acceptanceForm.drugName = row.drugName;
      this.acceptanceOpen = true;
      this.pendingOpen = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.purchaseId != null) {
            updatePurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 验收提交按钮 */
    submitAcceptance() {
      this.$refs["acceptanceForm"].validate(valid => {
        if (valid) {
          processAcceptance(this.acceptanceForm).then(response => {
            this.$modal.msgSuccess("验收成功");
            this.acceptanceOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseIds = row.purchaseId || this.ids;
      this.$modal.confirm('是否确认删除采购信息编号为"' + purchaseIds + '"的数据项？').then(function() {
        return delPurchase(purchaseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('veterinary/purchase/export', {
        ...this.queryParams
      }, `purchase_${new Date().getTime()}.xlsx`)
    },
    /** 待验收按钮操作 */
    handlePending() {
      getPendingList().then(response => {
        this.pendingList = response.data;
        this.pendingOpen = true;
      });
    },
    /** 打开库存选择对话框 */
    openInventorySelector() {
      this.inventorySelectorOpen = true;
      this.getInventoryList();
    },
    /** 获取库存列表 */
    getInventoryList() {
      listInventory(this.inventoryQuery).then(response => {
        this.inventoryList = response.rows;
        this.inventoryTotal = response.total;
      });
    },
    /** 重置库存查询 */
    resetInventoryQuery() {
      this.inventoryQuery = {
        pageNum: 1,
        pageSize: 10,
        drugName: null,
        batchNumber: null
      };
      this.getInventoryList();
    },
    /** 计算总金额 */
    calculateTotal() {
      if (this.form.quantity && this.form.purchasePrice) {
        this.form.totalAmount = (parseFloat(this.form.quantity) * parseFloat(this.form.purchasePrice)).toFixed(2);
      } else {
        this.form.totalAmount = "0.00";
      }
    },
    /** 选择库存商品 */
    selectInventoryItem(row) {
      // 自动填充表单字段
      this.form.drugName = row.drugName;
      this.form.drugSpecification = row.drugSpecification;
      this.form.batchNumber = row.batchNumber;
      this.form.purchasePrice = row.purchasePrice || 0;
      
      // 计算总金额
      this.calculateTotal();
      
      // 根据药品名称查找对应的厂家ID
      const matchedManufacturer = this.manufacturerList.find(m => 
        row.drugName && row.drugName.includes(m.manufacturerName)
      );
      if (matchedManufacturer) {
        this.form.manufacturerId = matchedManufacturer.manufacturerId;
      }
      
      // 关闭对话框
      this.inventorySelectorOpen = false;
      
      this.$message.success('已选择库存商品：' + row.drugName);
    }
  }
};
</script>

<style scoped>
.inventory-selector-table {
  cursor: pointer;
}

.inventory-selector-table .el-table__row:hover {
  background-color: #f5f7fa;
}

.inventory-selector-table .current-row {
  background-color: #ecf5ff;
}

.quick-select-btn {
  width: 100%;
}

.inventory-item-card {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.inventory-item-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.inventory-item-title {
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.inventory-item-info {
  color: #606266;
  font-size: 12px;
}

.inventory-search-form {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
}
</style>
